<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['spider:spiderField:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['spider:spiderField:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['spider:spiderField:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['spider:spiderField:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spiderFieldList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字段" align="center" prop="field" />
      <el-table-column label="字段名称" align="center" prop="fieldName" />
      <el-table-column label="提取类型" align="center" prop="extractType" :formatter="extractTypeFormat" />
      <el-table-column label="提取规则" align="center" prop="extractBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['spider:spiderField:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRule(scope.row)"
            v-hasPermi="['spider:fieldRule:add']"
          >配置规则</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['spider:spiderField:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置字段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段" prop="field">
              <el-input v-model="form.field" placeholder="请输入字段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="提取类型">
              <el-radio-group v-model="form.extractType">
                <el-radio
                  v-for="dict in extractTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="form.extractType==='constant'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="常量值" prop="constantValue">
                <el-input v-model="form.constantValue" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-else>
          <el-row>
            <el-col :span="24">
              <el-form-item label="提取规则(xpath,css值)" prop="extractBy">
                <el-input v-model="form.extractBy" placeholder="请输入提取规则" />
              </el-form-item>
            </el-col>
            <!--          <el-col :span="12">-->
            <!--            <el-form-item label="处理规则" prop="processRuleId">-->
            <!--              <el-input v-model="form.processRuleId" placeholder="请输入处理规则" />-->
            <!--            </el-form-item>-->
            <!--          </el-col>-->
          </el-row>
          <div v-if="form.extractType==='css'">
            <el-row>
              <el-col :span="24">
                <el-form-item label="元素的索引" prop="extractIndex">
                  <el-input v-model="form.extractIndex" placeholder="请输入元素的索引" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="根据元素取值" prop="extractAttrFlag">
                  <el-switch v-model="form.extractAttrFlag" active-value="1" inactive-value="0" @change="handleFlagChange()"  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="extractAttrVis">
              <el-col :span="24">
                <el-form-item label="根据哪个元素取值" prop="extractAttr">
                  <el-input v-model="form.extractAttr" placeholder="请输入根据哪个元素取值" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpiderField, getSpiderField, delSpiderField, addSpiderField, updateSpiderField, exportSpiderField } from "@/api/spider/spiderField";
import {changeJobStatus} from "@/api/monitor/job";

export default {
  name: "SpiderField",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配置字段表格数据
      spiderFieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 提取类型字典
      extractTypeOptions: [],
      // 根据元素取值字典
      extractAttrFlagOptions: [],
      // 查询参数
      queryParams: {
        configId:null,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 属性名显示
      extractAttrVis: false
    };
  },
  created() {
    if(this.form.configId != this.$route.query.configId){
      this.form.configId = this.$route.query.configId;
      this.queryParams.configId = this.$route.query.configId;
      this.getList();
    }
    this.getDicts("spider_extract_type").then(response => {
      this.extractTypeOptions = response.data;
    });
    this.getDicts("sys_switch_type").then(response => {
      this.extractAttrFlagOptions = response.data;
    });
  },
  activated(){
    if(this.form.configId != this.$route.query.configId){
      this.form.configId = this.$route.query.configId;
      this.queryParams.configId = this.$route.query.configId;
      this.getList();
    }
  },
  methods: {
    /** 查询配置字段列表 */
    getList() {
      this.loading = true;
      listSpiderField(this.queryParams).then(response => {
        this.spiderFieldList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 提取类型字典翻译
    extractTypeFormat(row, column) {
      return this.selectDictLabel(this.extractTypeOptions, row.extractType);
    },
    // 根据元素取值字典翻译
    extractAttrFlagFormat(row, column) {
      return this.selectDictLabel(this.extractAttrFlagOptions, row.extractAttrFlag);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fieldId: null,
        configId: null,
        field: null,
        fieldName: null,
        extractType: "0",
        extractBy: null,
        constantValue: null,
        extractIndex: null,
        processRuleId: null,
        extractAttrFlag: "0",
        extractAttr: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fieldId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配置字段";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fieldId = row.fieldId || this.ids
      getSpiderField(fieldId).then(response => {
        this.form = response.data;
        if (this.form.extractAttrFlag=="1")this.extractAttrVis=true;
        this.open = true;
        this.title = "修改配置字段";
      });
    },
    /** 修改按钮操作 */
    handleRule(row) {
      this.reset();
      const fieldId = row.fieldId || this.ids
      this.$router.push({ path: "/spider/fieldRule", query: { fieldId:fieldId} });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fieldId != null) {
            updateSpiderField(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpiderField(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fieldIds = row.fieldId || this.ids;
      this.$confirm('是否确认删除配置字段编号为"' + fieldIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSpiderField(fieldIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有配置字段数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSpiderField(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleFlagChange() {
      if (this.form.extractAttrFlag=="1"){
        this.extractAttrVis=true;
      } else {
        this.extractAttrVis=false;
      }
    },
  }
};
</script>
